package com.test;



import com.liferay.portal.PortalException;
import com.liferay.portal.SystemException;
import com.liferay.portal.model.User;
import com.liferay.portal.util.PortalUtil;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.portlet.GenericPortlet;
import javax.portlet.ActionRequest;
import javax.portlet.ReadOnlyException;
import javax.portlet.RenderRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderResponse;
import javax.portlet.PortletException;
import java.io.IOException;
import java.net.URLEncoder;
import javax.portlet.PortletMode;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.ValidatorException;
import javax.portlet.GenericPortlet;
import javax.portlet.ActionRequest;
import javax.portlet.RenderRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderResponse;
import javax.portlet.PortletException;
import java.io.IOException;
import java.net.URLEncoder;
import javax.portlet.PortletMode;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.ValidatorException;

import com.liferay.portal.util.PortalUtil;
import com.liferay.portal.model.User;
import com.projManage.service.service.projManagedbLocalServiceUtil;
import com.projManage.service.model.*;
import com.liferay.portal.kernel.servlet.SessionMessages;

/**
 * dotprojectPM Portlet Class
 */
public class dotprojectPM extends GenericPortlet {
    public static final String ACTION_CHANGESET = "changeset";
      public static final String ACTION_BROWSE = "browse";
      public static final String ACTION_PARAM = "action";
      public static final String ACTION_CHANGE = "change";
      public static final String ACTION_SAVE_SETTINGS = "save";


    @Override
    public void processAction(ActionRequest request, ActionResponse response) throws PortletException,IOException {
    String error = null;
        String success = null;
        PortletPreferences pref = request.getPreferences();

        if(request.getPortletMode().equals(PortletMode.EDIT)){
            boolean editOk = false;
            String url = request.getParameter("formUrl");
            String usrname = request.getParameter("formLoginUsrname");
             String passwd = request.getParameter("formLoginPasswd");
           
           
                if(url.equals("null")||usrname.equals("")||passwd.equals("")){
                    throw new ValidatorException("Set your dotProject Login correctly", null);
                }else{
                   //Get the portal userID of the current logged in user of the portal
            long portalUserId = 0;
            User currentUser = null;
            try {
                currentUser = PortalUtil.getUser(request);
                portalUserId = currentUser.getUserId();
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            Boolean existance = false;
            projManagedb user;
            try{
                //User with this id is already there in the service builder database. So only update the database
                user = projManagedbLocalServiceUtil.getprojManagedb(portalUserId);
                existance = true;
            }catch(Exception ex){
                //User with this id does not exists. So create a new entry.
                user = projManagedbLocalServiceUtil.createprojManagedb(portalUserId);
            }
            //Set the values in the table.
            user.setId(portalUserId);
            user.setUsername(usrname);
            user.setDpurl(url);
            user.setPassword(passwd);

            //Do the updation or adding a new entry according to the existance of the user.
            try {
                if(existance){
                    projManagedbLocalServiceUtil.updateprojManagedb(user);
                    System.out.println("User details updated");
                }else{
                    projManagedbLocalServiceUtil.updateprojManagedb(user);
                    System.out.println("User is added");
                }
                editOk = true;
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            if(editOk){
                success = "Successfully stored the preferences.";
                response.setRenderParameter("success", URLEncoder.encode(success, "UTF-8"));
            }else{
                error = "Unsuccessful in storing the preferences";
                response.setRenderParameter("error", URLEncoder.encode(error, "UTF-8"));
            }
        }

        }
        if(request.getPortletMode().equals(PortletMode.VIEW)){
            String edit = request.getParameter("edit");
            if(edit.equals("link")){
                response.setPortletMode(PortletMode.EDIT);
            }else{
            }
        }
        }

   
    
    @Override
    public void doView(RenderRequest request,RenderResponse response) throws PortletException,IOException {
        try {
            User currentUser = null;
            currentUser = PortalUtil.getUser(request);
            String a = currentUser.getLogin();
            String sname = currentUser.getScreenName();
            PortletPreferences pref = request.getPreferences();
            String url = pref.getValue("dpUrl", "null");
            String login = pref.getValue("dpLogin", "null");
            request.setAttribute("DP_URL", url);
            request.setAttribute("DP_LOGIN", login);
            String action = request.getParameter(ACTION_PARAM);
            if (ACTION_CHANGESET.equals(action)) {
                doChangeSet(request, response);
            } else if (ACTION_BROWSE.equals(action)) {
                doBrowse(request, response);
            }else if (ACTION_CHANGE.equals(action)) {
                doChange(request, response);
            }else if(ACTION_SAVE_SETTINGS.equals(action)){
                doSave(request,response);
            }


            else {
                response.setContentType("text/html");
                PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher("/WEB-INF/jsp/dotprojectPM_view.jsp");
                dispatcher.include(request, response);
            }
        } catch (PortalException ex) {
            Logger.getLogger(dotprojectPM.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SystemException ex) {
            Logger.getLogger(dotprojectPM.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void doHelp(RenderRequest request, RenderResponse response) throws PortletException,IOException {

        response.setContentType("text/html");
        PortletRequestDispatcher dispatcher =
        getPortletContext().getRequestDispatcher("/WEB-INF/jsp/dotprojectPM_help.jsp");
        dispatcher.include(request, response);
    }
    @Override
    public void doEdit(RenderRequest request,RenderResponse response) throws PortletException,IOException {
            response.setContentType("text/html");        
        PortletRequestDispatcher dispatcher =
        getPortletContext().getRequestDispatcher("/WEB-INF/jsp/dotprojectPM_edit.jsp");
        dispatcher.include(request, response);
    }
    private void doBrowse(RenderRequest request, RenderResponse response) {
        try {
            response.setContentType("text/html");
            PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher("/WEB-INF/jsp/dotprojectPM_view.jsp");
            dispatcher.include(request, response);
        } catch (PortletException ex) {
            Logger.getLogger(dotprojectPM.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(dotprojectPM.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private void doChangeSet(RenderRequest request, RenderResponse response) throws PortletException {
       try {
            String action = request.getParameter(ACTION_PARAM);

        // first - check for save-action before checking ofr repositoryLocation
        if (ACTION_SAVE_SETTINGS.equals(action)) {
            doSave(request, response);
        }
             // read path and set it
       try{

       PortletPreferences prefs = request.getPreferences();


       String pname2 = prefs.getValue("pname", null);
        String rname2 = prefs.getValue("rname", null);
        String rlocation2 = prefs.getValue("rpath", null);
        String plocation2= prefs.getValue("plocation", null);


        //String scmUsn = prefs.getValue(PREF_SCM_USN, null);
        request.setAttribute("pname", pname2);
        request.setAttribute("rname", rname2);
        request.setAttribute("rpath" , rlocation2);
        request.setAttribute("plocation", plocation2);


    }catch(Exception ex){
        System.out.println(ex.getMessage());
    }

            response.setContentType("text/html");
            PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher("/WEB-INF/jsp/repojsp.jsp");

            dispatcher.include(request, response);
        } catch (Exception ex) {
            throw new PortletException("Cannot get changeset", ex);
        }
    }

    private void doChange(RenderRequest request, RenderResponse response) {
          try{

        response.setContentType("text/html");
            PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher("/WEB-INF/jsp/repo.jsp");

            dispatcher.include(request, response);
        } catch (Exception ex) {
            try {
                throw new PortletException("Cannot get change", ex);
            } catch (PortletException ex1) {
                Logger.getLogger(dotprojectPM.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }
    }

    private void doSave(RenderRequest request, RenderResponse response) {
        try {
            String pname1 = request.getParameter("pname");
            String rname1 = request.getParameter("rname");
            String rlocation1 = request.getParameter("rpath");
            String plocation1 = request.getParameter("plocation");
            PortletPreferences prefs = request.getPreferences();
            prefs.setValue("pname", pname1);
            prefs.setValue("rname", rname1);
            prefs.setValue("rpath", rlocation1);
            prefs.setValue("plocation", plocation1);
            prefs.store();
        } catch (IOException ex) {
            Logger.getLogger(dotprojectPM.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ValidatorException ex) {
            Logger.getLogger(dotprojectPM.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ReadOnlyException ex) {
            Logger.getLogger(dotprojectPM.class.getName()).log(Level.SEVERE, null, ex);
        }
        SessionMessages.add(request, "success");
    }
}